$NG.AllReady(function (listPage, { useValuesChange, useUpdateRows, useBeforeClick, useUpdateRow, useDataIndexChange, useClick }) {
    console.log(listPage);
    console.log("list Ready");
    const { origin, pathname } = window.location;
    console.log(`${origin}`);

    // const baseUrl = "http://nginx.clouddev.hisense.com/react/index.html";
    const queryParams = {
        id: "8570000000000001",
        otype: "view",
        busType: "EFORM9000000201",
        isSso: "1",
        AppTitle: "定价需求池",
    }; // 构造查询字符串

    const queryString = new URLSearchParams(queryParams).toString();
    const url = `${origin}${pathname}#/customform/detail?${queryString}`; // 打开URL // $NG.open(url, { AppTitle: "定价需求池" });

    window.location.href = url;
    function softRefresh() {
        const url = new URL(window.location.href);
        url.searchParams.set('refresh', Date.now());
        window.history.replaceState({}, '', url);
    }
    softRefresh()
    ////////////////////////////////////////--获取组件实例
    const mstform = $NG.getCmpApi("p_form_zyxqc");
    const dgrid = $NG.getCmpApi("p_form_zyxqc_d1");
    const dgrid1 = $NG.getCmpApi("p_form_zyxqc_d1");
    const toolbar_top = $NG.getCmpApi("toolbar_top");
    const toolbar_dgrid1 = $NG.getCmpApi("toolbar_p_form_zyxqc_d1");

    var formToolbar = $NG.getCmpApi("toolbar_top");
    console.log(formToolbar, mstform);

    var btn = ["save", "imp_push", "imp_push_his"];
    for (let index = 0; index < btn.length; index++) {
        formToolbar.hideButton(btn[index]);
    }

    if (toolbar_top) {
        ////////////////////////////////////////--添加按钮 指派招标人

        ////////////////////////////////////////--隐藏按钮 保存
        toolbar_top.setHidden("imp", "imppush", "import", "save", "attachment", "check", "history", "applycheck");

        useClick(async function ({ args }) {
            // 创建遮罩层
            let rows = $NG.getCmpApi('p_form_zyxqc_d1').getSelectedData();
            console.log(rows);

            if (rows.length < 1) {
                $NG.alert('请先选择数据')
                return
            }
            if (!rows.every(item => item.u_staus === '待定价')) {
                $NG.alert('只能驳回状态为【待定价】的数据');
                return;
            }
            const overlay = document.createElement('div');
            overlay.style = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
      `;

            // 创建弹窗容器
            const modal = document.createElement('div');
            modal.style = `
        background: white;
        padding: 24px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        width: 500px;
        animation: slideIn 0.3s ease;
      `;

            // 弹窗内容
            modal.innerHTML = `
        <h3 style="margin:0 0 16px; color: #333; font-size: 18px;">驳回确认</h3>
        <p style="margin:0 0 16px; color: #666;">请填写驳回原因：</p>
        <textarea 
          id="rejectReason" 
          style="
            width: 100%;
            height: 80px;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 16px;
            resize: vertical;
          "
          placeholder="请输入驳回原因..."
        ></textarea>
        <div style="display: flex; justify-content: flex-end; gap: 8px;">
          <button id="cancelBtn" style="
            padding: 8px 16px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: white;
            cursor: pointer;
          ">取消</button>
          <button id="confirmBtn" style="
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            background: #1890ff;
            color: white;
            cursor: pointer;
          ">确认驳回</button>
        </div>
      `;

            // 添加到页面
            overlay.appendChild(modal);
            document.body.appendChild(overlay);
            const errorMsg = modal.querySelector('#errorMsg') || document.createElement('div'); // 获取或创建错误提示

            // 清空旧提示
            errorMsg.innerHTML = '';
            // 添加动画
            const style = document.createElement('style');
            style.innerHTML = `
        @keyframes slideIn {
          from { transform: translateY(-20px); opacity: 0; }
          to { transform: translateY(0); opacity: 1; }
        }
      `;
            document.head.appendChild(style);

            // 绑定事件
            const confirmBtn = modal.querySelector('#confirmBtn');
            const cancelBtn = modal.querySelector('#cancelBtn');
            const textarea = modal.querySelector('#rejectReason');

            // 确认驳回逻辑
            confirmBtn.onclick = () => {
                const reason = textarea.value.trim();
                if (reason) {
                    let rows = $NG.getCmpApi('p_form_zyxqc_d1').getSelectedData();
                    const promises = rows.map(row => {
                        return new Promise((resolve, reject) => {
                            const bhStatus = row.u_source_table === 'mat_p_d' ? 'user_dj_status' : 'u_dj_status';
                            const bhReason = row.u_source_table === 'mat_p_d' ? 'user_bhyy' : 'u_bhyy';
                            const sql = `${bhStatus}=4,${bhReason}='${reason}'`;
                            $NG.execServer(
                                "UPDATE",
                                {
                                    tbname: row.u_source_table,
                                    sqlStr: sql,
                                    queryStr: `phid = ${row.phid}`
                                },
                                (res) => {
                                    if (res.status === 'success') {
                                        resolve(); // 标记为成功
                                    } else {
                                        reject();   // 标记为失败
                                    }
                                }
                            );
                        });
                    });
                    Promise.all(promises)
                        .then(() => {
                            $NG.alert('驳回成功！'); // 统一弹窗
                            document.body.removeChild(overlay);
                            document.head.removeChild(style);
                        })
                        .catch(() => {
                            $NG.alert('部分数据修改失败，请检查日志'); // 失败提示（可选）
                        });
                    // $NG.alert('驳回原因不能为空');
                    return;
                } else {
                    // 创建错误提示元素
                    errorMsg.id = 'errorMsg';
                    errorMsg.style = `
            color: #ff4d4f;
            font-size: 12px;
            margin: -8px 0 12px;
            padding-left: 4px;
        `;
                    errorMsg.textContent = '驳回原因不能为空';

                    // 插入到文本域下方
                    if (!modal.contains(errorMsg)) {
                        textarea.parentNode.insertBefore(errorMsg, textarea.nextSibling);
                    }
                    return; // 阻止继续执行
                }


            };

            // 取消逻辑
            const closeModal = () => {
                document.body.removeChild(overlay);
                document.head.removeChild(style);
            };

            cancelBtn.onclick = closeModal;
            // overlay.onclick = (e) => {
            //   if (e.target === overlay) closeModal();
            // };
        }, "sendPerson");
        useClick(async function ({ args }) {
            //按钮点击事件
            let rows = $NG.getCmpApi('p_form_zyxqc_d1').getSelectedData();
            if (rows.length < 1) {
                $NG.alert('请先选择数据')
                return
            }
            editPer()
        }, "editPerson");
    }

    ////////////////////////////////////////-- 添加按钮 查询
    if (toolbar_dgrid1) {
        // toolbar_dgrid1.insert({
        //   id: "u_search",
        //   text: "查询",
        //   iconCls: "icon-New",
        // });
        toolbar_dgrid1.insert({
            id: "sendPerson",
            text: "定价驳回",
            iconCls: "icon-New",
        });
        toolbar_dgrid1.insert({
            id: "editPerson",
            text: "修改定价负责人",
            iconCls: "icon-New",
        });
        toolbar_dgrid1.insert({
            id: "u_push1",
            text: "下推定价方案",
            iconCls: "icon-New",
        });
        toolbar_dgrid1.insert({
            id: "u_push10",
            text: "下推定价结果导入",
            iconCls: "icon-New",
        });
        toolbar_dgrid1.insert({
            id: "u_push2",
            text: "下推询价单",
            iconCls: "icon-New",
        });
        toolbar_dgrid1.insert({
            id: "u_push3",
            text: "下推采购合同",
            iconCls: "icon-New",
        });
        toolbar_dgrid1.insert({
            id: "u_output",
            text: "模板下载",
            iconCls: "icon-InsertRow"
        });
        useClick(async function ({ args }) {
            const baseUrl = `${origin}`;
            const queryParams = {
                // id: "8570000000000001",
                // otype: "view",
                // busType: "EFORM9000000201",
                // isSso: "1",
                rep_id: "8570000000000026",
                defaultSheet: 0,
                name: '定价需求模板',
                menucode: 'd820cfd6-a526-441d-a23d-a28bdeea3fe8',
                AppTitle: "模板下载",
            }; // 构造查询字符串

            const queryString = new URLSearchParams(queryParams).toString();
            const url = `${origin}/report/index.html#/tableDesign/TableManager/preview?${queryString}`;
            console.log(url);

            // 打开报表并传递参数
            $NG.open(url, { AppTitle: "模板下载" });
        }, "u_output");

        //按钮点击前事件
        useBeforeClick(async function ({ args }) {
            const existingRows = $NG.getCmpApi('p_form_zyxqc_d1').getRows();//获取表体所有行
            const rows = $NG.getCmpApi('p_form_zyxqc_d1').getSelectedData();//获取表体选中行
            console.log(existingRows);
            console.log(rows);
            if (rows.length > 0) {
                // 提取选中行的所有 u_code 并去重
                const selectedCodes = [...new Set(rows.map(row => row.u_code))];
                console.log(selectedCodes);

                // 检查每个 u_code 是否全部选中
                const uncompletedCodes = [];
                for (const code of selectedCodes) {
                    // 获取该 u_code 在 existingRows 中的所有行
                    const allSameCodeRows = existingRows.filter(row => row.u_code === code);
                    console.log(allSameCodeRows);

                    // 检查这些行是否都被选中
                    const allSelected = allSameCodeRows.every(row =>
                        rows.some(selectedRow => selectedRow.phid === row.phid) // 用 phid 判断行对象一致性
                    );
                    console.log(allSelected);

                    if (!allSelected) {
                        uncompletedCodes.push(code);
                    }
                }
                console.log(uncompletedCodes);

                // 如果有未完整选中的 u_code
                if (uncompletedCodes.length > 0) {
                    $NG.alert(`以下单据号为全部选中：${uncompletedCodes.join(', ')}`);
                    await new Promise(resolve => setTimeout(resolve, 2000));
                    // return false; // 阻止后续执行
                }
            }
            // return false
            selectedUSourceData();
            const url = new URL(window.location.href);
            url.searchParams.set("biaoshi", "true"); // 添加标识
            window.history.replaceState({}, "", url.toString());
        }, "u_push1");
        useBeforeClick(async function ({ args }) {

            selectedUSourceData();
        }, "u_push2");
        useBeforeClick(async function ({ args }) {
            try {
                // 获取选中行数据
                const rows = $NG.getCmpApi('p_form_zyxqc_d1').getSelectedData();
                if (!rows || rows.length === 0) {
                    $NG.alert('请先选择数据');
                    return false; // 阻止后续执行
                }
                const firstPnum = rows[0].u_pnum;
                const isPnumConsistent = rows.every(row =>
                    String(row.u_pnum) === String(firstPnum) // 统一转为字符串比较
                );

                if (!isPnumConsistent) {
                    $NG.alert('勾选物料明细所属项目名称不一致，不能发起合同！');
                    return false;
                }
                const isValidSource = rows.every(row =>
                    row.u_source === '采购申请' ||
                    row.u_source === '备品备件采购申请'
                );

                if (!isValidSource) {
                    $NG.alert('只能选择【采购申请】或【备品备件采购申请】来源的数据下推采购合同！');
                    return false; // 阻止后续执行
                }
                // 并行查询每行的状态
                const statusChecks = rows.map(row => {
                    return new Promise((resolve, reject) => {
                        const billNo = row.u_code;
                        const billName = row.u_source;
                        let gnkz;

                        if (billName !== '采购申请') {
                            gnkz = 'searchBpbjDjzt';
                        } else {
                            gnkz = 'searchDjzt';
                        }
                        console.log(`"${gnkz}"`);
                        $NG.execServer(`${gnkz}`, { bill_no: `'${billNo}'` }, (res) => {
                            try {
                                if (res.status !== 'success' || !res.data) {
                                    throw new Error(`接口返回异常: ${billNo}`);
                                }
                                // 解析 JSON 数据
                                const data = JSON.parse(res.data);
                                if (!Array.isArray(data)) {
                                    throw new Error(`数据格式非数组: ${billNo}`);
                                }

                                // 检查所有条目状态
                                const allValid = data.every(item => {
                                    const isValid = item.extendObjects.user_dj_status == 3;
                                    if (!isValid) {
                                        console.warn(`单据 ${billNo} 中存在异常状态:`, item);
                                    }
                                    return isValid;
                                });

                                resolve(allValid); // 全部为3则true，否则false
                            } catch (error) {
                                console.error(`处理失败 [${billNo}]:`, error);
                                reject(error);
                            }
                        });
                    });
                });

                // 等待所有状态检查完成
                const results = await Promise.all(statusChecks);
                const allValid = results.every(isValid => isValid === true);
                if (!allValid) {
                    // $NG.alert('存在未完成定价的数据');
                    const shouldContinue = await new Promise((resolve) => {
                        const overlay = document.createElement('div');
                        overlay.style = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
          `;

                        // 创建弹窗容器
                        const modal = document.createElement('div');
                        modal.style = `
            background: white;
            padding: 24px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            width: 500px;
            animation: slideIn 0.3s ease;
          `;

                        // 弹窗内容
                        modal.innerHTML = `
            <h3 style="margin:0 0 16px; color: #333; font-size: 16px;">存在为完成定价的数据，是否继续下推采购合同</h3>
    
            <div style="display: flex; justify-content: flex-end; gap: 8px;">
              <button id="cancelBtn" style="
                padding: 8px 16px;
                border: 1px solid #ddd;
                border-radius: 4px;
                background: white;
                cursor: pointer;
              ">取消</button>
              <button id="confirmBtn" style="
                padding: 8px 16px;
                border: none;
                border-radius: 4px;
                background: #1890ff;
                color: white;
                cursor: pointer;
              ">确认</button>
            </div>
          `;

                        // 添加到页面
                        overlay.appendChild(modal);
                        document.body.appendChild(overlay);
                        const errorMsg = modal.querySelector('#errorMsg') || document.createElement('div'); // 获取或创建错误提示

                        // 清空旧提示
                        errorMsg.innerHTML = '';
                        // 添加动画
                        const style = document.createElement('style');
                        style.innerHTML = `
            @keyframes slideIn {
              from { transform: translateY(-20px); opacity: 0; }
              to { transform: translateY(0); opacity: 1; }
            }
          `;
                        document.head.appendChild(style);

                        // 绑定事件
                        const confirmBtn = modal.querySelector('#confirmBtn');
                        const cancelBtn = modal.querySelector('#cancelBtn');

                        // 确认驳回逻辑
                        confirmBtn.onclick = () => {
                            document.body.removeChild(overlay);
                            document.head.removeChild(style);
                            resolve(true); // 用户确认继续
                        };
                        // 取消逻辑
                        const closeModal = () => {
                            document.body.removeChild(overlay);
                            document.head.removeChild(style);
                            resolve(false); // 用户取消操作
                        };
                        cancelBtn.onclick = closeModal;
                    })
                    if (!shouldContinue) {
                        return false; // 拦截后续流程
                    }
                }
                selectedUSourceData();
                // 主表状态校验
                // if (mstform.getItem('u_status').getValue() === '定价完成') {
                //   return true; // 允许继续执行
                // } else {
                //   // $NG.alert('主表状态不符合要求');
                //   // return false;
                // }
            } catch (error) {
                console.error('操作失败:', error);
                $NG.alert('状态校验异常，请检查数据');
                return false;
            }
        }, "u_push3");

        function editPer(params) {
            try {
                $NG.external
                    .openNGHelp({
                        type: "NGSingleHelp",
                        helpId: 'eam3_hr_epm_main',
                        valueField: "phid",
                        labelField: "bill_name",
                        // clientSqlFilter: "phid_pc = " + phid_pc,
                    })
                    .then((data) => {
                        if (!data) return;
                        let rows = $NG.getCmpApi('p_form_zyxqc_d1').getSelectedData();
                        const promises = rows.map(row => {
                            return new Promise((resolve, reject) => {
                                const bname = row.u_source_table === 'mat_p_d' ? 'user_djfzr' : 'u_djfzr';
                                const sql = `${bname}=${data.origin.PhId}`;
                                $NG.execServer(
                                    "UPDATE",
                                    {
                                        tbname: row.u_source_table,
                                        sqlStr: sql,
                                        queryStr: `phid = ${row.phid}`
                                    },
                                    (res) => {
                                        if (res.status === 'success') {
                                            row.u_director_phid = data.origin.PhId;
                                            row.u_director_phid_EXName = data.origin.CName;
                                            resolve(); // 标记为成功
                                        } else {
                                            reject();   // 标记为失败
                                        }
                                    }
                                );
                            });
                        });
                        Promise.all(promises)
                            .then(() => {
                                $NG.alert('修改成功！'); // 统一弹窗
                                dgrid.refreshView()
                                // setTimeout(() => {
                                //   location.reload()
                                // }, 1000);
                            })
                            .catch(() => {
                                $NG.alert('部分数据修改失败，请检查日志'); // 失败提示（可选）
                            });
                    });
            } catch (error) {
                $NG.alert("修改失败,请联系技术人员处理");
            }

        }


        function selectedUSourceData(params) {
            const dgrid1 = $NG.getCmpApi("p_form_zyxqc_d1");
            // 获取选中的数据
            const selectedData = dgrid1.getSelectedData();
            if (selectedData && selectedData.length > 0) {
                // 提取 u_source_id 和 u_source_table
                const extractedData = selectedData.reduce((value,item) => {
                    if ((Number(item.u_qdht_restqty) || 0) != 0) {
                        value.push({
                            u_source_id: item.u_source_id,
                            u_source_table: item.u_source_table,
                            u_director_phid: item.u_director_phid,
                            u_director_phid_EXName: item.u_director_phid_EXName,
                            u_pnum: item.u_pnum,
                            u_pname: item.u_pname,
                            phid_xl: item.phid_xl,
                            u_ps_prc_vat: item.u_ps_prc_vat,
                            u_sfyztj: item.u_source

                        })
                    }
                    return value
                },[]);
                if(extractedData.length == 0 ){
                    $NG.alert("除去为零的明细数据，您没有选中任何行！")
                    throw '停止运行'
                }
                localStorage.removeItem("selectedUSourceData");
                console.log("LocalStorage 已清除");
                // 存储到 LocalStorage
                localStorage.setItem("selectedUSourceData", JSON.stringify(extractedData));

                console.log("已存入 LocalStorage：", extractedData);
            } else {
                console.log("没有选中的数据");
            }
        }

        useClick(function ({ args }) {
            let rows = $NG.getCmpApi('p_form_zyxqc_d1').getSelectedData();
            if (rows.length < 1) {
                $NG.alert('请先选择数据')
                return
            }
            const url_domain = `${origin}`; // 域名
            // const url_domain = "http://nginx.clouddev.hisense.com"; // 域名
            const url_path = "/react/index.html#/customform/detail"; // 路径
            const url_params = "?otype=add&busType=EFORM9000000160&isSso=0"; // 参数
            const schemeId = "&schemeId=8570000000000338";
            // const treeOcode = "&treeOcode=1";
            const treeOcodeName = "&treeOcodeName=%E6%B5%B7%E4%BF%A1%E9%9B%86%E5%9B%A2";
            const treePc = "&treePc=8570000000000123";
            const treePcName = "&treePcName=2025%E5%B9%B4%E6%B5%8B%E8%AF%95%E9%A1%B9%E7%9B%AE%EF%BC%88%E5%8B%BF%E7%94%A8%EF%BC%81%EF%BC%81%EF%BC%81%EF%BC%89";
            const menucode = "&menucode=eb950c2f-9855-46c8-82a8-85d9bfe9c2a9";
            const currentParams = new URLSearchParams(window.location.search);
            const biaoshiParam = currentParams.get("biaoshi") ? `&biaoshi=${currentParams.get("biaoshi")}` : "";
            $NG.open(url_domain + url_path + url_params + schemeId + treeOcodeName + treePc + treePcName + menucode + biaoshiParam, { AppTitle: "定价方案-新增" });
        }, "u_push1");
        useClick(function ({ args }) {
            let rows = $NG.getCmpApi('p_form_zyxqc_d1').getSelectedData();
            if (rows.length < 1) {
                $NG.alert('请先选择数据')
                return
            }
            selectedUSourceData();
            // 'http://nginx.clouddev.hisense.com/react/index.html#/customform/detail?otype=add&busType=EFORM9000000212&isSso=0&&treeOcode=1&treeOcodeName=%E6%B5%B7%E4%BF%A1%E9%9B%86%E5%9B%A2&treePc=&treePcName=&menucode=96da252c-0f6d-4629-8647-83798ee733bf'
            const url_domain = `${origin}`; // 域名
            // const url_domain = "http://nginx.clouddev.hisense.com"; // 域名
            const url_path = "/react/index.html#/customform/detail"; // 路径
            const url_params = "?otype=add&busType=EFORM9000000212&isSso=0"; // 参数
            const schemeId = "&schemeId=8570000000000338";
            // const treeOcode = "&treeOcode=1";
            const treeOcodeName = "&treeOcodeName=%E6%B5%B7%E4%BF%A1%E9%9B%86%E5%9B%A2";
            const treePc = "&treePc=";
            const treePcName = "&treePcName=";
            const menucode = "&menucode=96da252c-0f6d-4629-8647-83798ee733bf";
            // const currentParams = new URLSearchParams(window.location.search);
            // const biaoshiParam = currentParams.get("biaoshi") ? `&biaoshi=${currentParams.get("biaoshi")}` : "";
            $NG.open(url_domain + url_path + url_params + schemeId + treeOcodeName + treePc + treePcName + menucode, { AppTitle: "定价结果导入-新增" });
        }, "u_push10");
        useClick(function ({ args }) {
            let rows = $NG.getCmpApi('p_form_zyxqc_d1').getSelectedData();
            if (rows.length < 1) {
                $NG.alert('请先选择数据')
                return
            }
            const url_domain = `${origin}`; // 域名
            // const url_domain = "http://nginx.clouddev.hisense.com"; // 域名
            const url_path = "/react/index.html#/customform/detail"; // 路径
            const url_params = "?otype=add&busType=EFORM9000000160&isSso=0"; // 参数
            const schemeId = "&schemeId=8570000000000338";
            // const treeOcode = "&treeOcode=1";
            const treeOcodeName = "&treeOcodeName=%E6%B5%B7%E4%BF%A1%E9%9B%86%E5%9B%A2";
            const treePc = "&treePc=8570000000000123";
            const treePcName = "&treePcName=2025%E5%B9%B4%E6%B5%8B%E8%AF%95%E9%A1%B9%E7%9B%AE%EF%BC%88%E5%8B%BF%E7%94%A8%EF%BC%81%EF%BC%81%EF%BC%81%EF%BC%89";
            const menucode = "&menucode=eb950c2f-9855-46c8-82a8-85d9bfe9c2a9";
            const currentParams = new URLSearchParams(window.location.search);
            const biaoshiParam = currentParams.get("biaoshi") ? `&biaoshi=${currentParams.get("biaoshi")}` : "";
            $NG.open(url_domain + url_path + url_params + schemeId + treeOcodeName + treePc + treePcName + menucode + biaoshiParam, { AppTitle: "定价方案-新增" });
        }, "u_push1");

        useClick(function ({ args }) {
            let rows = $NG.getCmpApi('p_form_zyxqc_d1').getSelectedData();
            if (rows.length < 1) {
                $NG.alert('请先选择数据')
                return
            }
            const url_domain = `${origin}`; // 域名
            // const url_domain = "http://nginx.clouddev.hisense.com"; // 域名
            const url_path = "/PMS/PMM/CG/CgXunjM/CgXunjMEdit"; // 路径
            const url_params = "?otype=add&ocode=1&defaultpc=8570000000000123&PublishPlatform=uic"; // 参数
            $NG.open(url_domain + url_path + url_params, { AppTitle: "询价单-新增" });
        }, "u_push2");
        useClick(function ({ args }) {

            const url_domain = `${origin}`; // 域名
            // const url_domain = "http://nginx.clouddev.hisense.com"; // 域名
            const url_path = "/PMS/PCM/CntM/CntMEditSev"; // 路径
            const url_params = "?otype=add&model=7&schemeid=8570000000000044&cnttype=8570000000000006&ocode=1&defaultpc=&queryFieldVal=undefined&menuCode=&ListFilterVal=&FunctionName=&"; // 参数
            $NG.open(url_domain + url_path + url_params, { AppTitle: "采购合同信息-新增" });


        }, "u_push3");

        // &Authorization=ngTokenKey%24NEWGRAND-WEB%241741913973000%240b2a6e86-ca93-4da8-8bbd-885e22adbe1a%24ja
    }
    let formShow = ["phid_pc", "u_status", "u_sjh", "app_dt", "u_djly", "u_director"];
    $NG.updateUI((updater) => {
        updater.fieldSetForm.p_form_zyxqc.u_ishtsyl.setProps({
            disabled: false, //只读
        });
    });
    $NG.updateUI((updater) => {
        updater.fieldSetForm.p_form_zyxqc.phid_pc.setProps({
            disabled: false, //只读
        });
    });
    $NG.updateUI((updater) => {
        updater.fieldSetForm.p_form_zyxqc.u_djno.setProps({
            disabled: false, //只读
        });
    });
    $NG.updateUI((updater) => {
        updater.fieldSetForm.p_form_zyxqc.u_material_s.setProps({
            disabled: false, //只读
        });
    });
    $NG.updateUI((updater) => {
        updater.fieldSetForm.p_form_zyxqc.u_status.setProps({
            disabled: false, //只读
        });
    });
    $NG.updateUI((updater) => {
        updater.fieldSetForm.p_form_zyxqc.u_sjh.setProps({
            disabled: false, //只读
        });
    });
    $NG.updateUI((updater) => {
        updater.fieldSetForm.p_form_zyxqc.app_dt.setProps({
            disabled: false, //只读
        });
    });
    $NG.updateUI((updater) => {
        updater.fieldSetForm.p_form_zyxqc.u_djly.setProps({
            disabled: false, //只读
        });
    });
    $NG.updateUI((updater) => {
        updater.fieldSetForm.p_form_zyxqc.u_director.setProps({
            disabled: false, //只读
        });
    });
    mstform.getItem("u_status").setValue({
        value: "待定价",
        label: "待定价",
    });
    mstform.getItem("u_ishtsyl").setValue('2');
    if (mstform) {
        const localStorageEQ = localStorage.getItem("localStorageEQ");
        if (localStorageEQ) {
            const parseEQ = JSON.parse(localStorageEQ);
            mstform.getItem("phid_pc").setValue({
                value: parseEQ[0].phid_pc,
                label: parseEQ[0].phid_pc_name,
            });
            mstform.getItem("u_status").setValue({
                value: parseEQ[0].u_status,
                label: parseEQ[0].u_status,
            });
            localStorage.removeItem("localStorageEQ");
            console.log("localStorageEQ 已清除");
        }

        useValuesChange(
            ({ args }) => {
                $NG.execServer("searchBillno", { phid: `'${mstform.getItem("u_djno").getValue()}'` }, function (res) {
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    if (res.count > 0) {
                        let bill_no1 = datas.bill_no
                    }
                });
            },
            ["p_form_zyxqc.u_djno"]
        );
        useValuesChange(
            ({ args }) => {
                console.log(args, "可以监听");
                getDjxqc();
                clientDjbh()
                dgrid.refreshView();
            },
            ["p_form_zyxqc.phid_pc", "p_form_zyxqc.u_djno", "p_form_zyxqc.u_ishtsyl", "p_form_zyxqc.u_status", "p_form_zyxqc.u_sjh", "p_form_zyxqc.u_djly", "p_form_zyxqc.app_dt", "p_form_zyxqc.u_director", "u_material_s"]
        );
        useValuesChange(({ args }) => {
            clientDjbh()
        }, "p_form_zyxqc.u_djly");
        function clientDjbh(params) {
            const phidPc = mstform.getItem('phid_pc').getValue() || '';
            if (mstform.getItem('u_djly').getValue() == '采购申请') {
                // if (!mstform.getItem('phid_pc').getValue()) {
                //   $NG.alert('选择采购申请前请先选择项目')
                //   mstform.getItem('u_djly').setValue('')
                // }else{
                $NG.updateUI((updater) => {
                    const fields = ["u_djno"];
                    fields.forEach((field) => {
                        updater.fieldSetForm.p_form_zyxqc[field].setProps({
                            clientSqlFilter: `phid_pc like'${phidPc}%'`, //过滤条件
                        });
                    });
                });
                // }
            } else {
                $NG.updateUI((updater) => {
                    const fields = ["u_djno"];
                    fields.forEach((field) => {
                        updater.fieldSetForm.p_form_zyxqc[field].setProps({
                            clientSqlFilter: ``, //过滤条件
                        });
                    });
                });
            }

        }
        function toUTC(dateStr) {
            const date = new Date(dateStr);
            return date.toISOString().slice(0, 19).replace('T', ' ');
        }
        async function getDjxqc() {
            let sqlFilter = `1=1`;

            if (mstform.getValues().phid_pc) {
                let pcid = mstform.getItem("phid_pc").getValue();
                sqlFilter += ` and phid_pc = '${pcid}'`; // 用单引号包裹
            }
            if (mstform.getValues().u_djno) {
                const phid = mstform.getItem("u_djno").getValue();

                // 使用 Promise 封装异步操作
                const billNo = await new Promise((resolve, reject) => {
                    $NG.execServer("searchBillno", { phid: `'${phid}'` }, (res) => {
                        try {
                            if (res.status !== 'success' || res.count === 0) {
                                throw new Error('未查询到数据');
                            }

                            const datas = JSON.parse(res.data)[0]?.extendObjects;
                            if (!datas?.bill_no) {
                                throw new Error('bill_no 字段缺失');
                            }

                            resolve(datas.bill_no); // 返回需要的值
                        } catch (e) {
                            console.error('处理失败:', e);
                            reject(e);
                        }
                    });
                });

                sqlFilter += ` and bill_no = '${billNo}'`; // 正确拼接
            }
            if (mstform.getValues().u_djly) {
                let djly = mstform.getItem("u_djly").getValue();
                sqlFilter += ` and djly = '${djly}'`; // 也是用单引号包裹
            }
            if (mstform.getValues().u_ishtsyl) {

                const btnValue = mstform.getItem("u_ishtsyl").getValue();

                if (btnValue == '2') {

                    sqlFilter += ' and rest_qty > 0';

                } else if (btnValue == '1') {

                    sqlFilter += ' and rest_qty = 0';

                }

            }
            if (mstform.getValues().u_material_s) {
                let material_s = mstform.getItem("u_material_s").getValue();
                sqlFilter += ` and phid_xl = '${material_s}'`; // 也是用单引号包裹
            }
            if (mstform.getValues().app_dt) {
                let app_dt = mstform.getItem("app_dt").getValue();
                sqlFilter += ` and app_dt like '${app_dt}%' `;
            }
            if (mstform.getValues().u_sjh) {
                let u_sjh = mstform.getItem("u_sjh").getValue();
                sqlFilter += ` and phid_sj = '${u_sjh}'`; // 也是用单引号包裹
            }
            if (mstform.getValues().u_director) {
                let u_director = mstform.getItem("u_director").getValue();
                sqlFilter += ` and hr_phid= '${u_director}'`; // 也是用单引号包裹
            }
            console.log(`'${mstform.getValues().u_status}' and ${sqlFilter}`);

            if (dgrid) {
                dgrid.clearRows();
                await $NG.execServer("getDjxqc", { u_staus: `'${mstform.getValues().u_status}%' and ${sqlFilter}` }, function (res) {
                    if (res.count === 0) {
                        dgrid.clearRows();
                    }
                    if (!res.data) return
                    const data = JSON.parse(res.data);
                    //默认增行,批量新增表体数据
                    var gridArr = []; //定义表体数组
                    var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
                    for (var i = 0; i < gridCount; i++) {
                        var gridObj = {};
                        //对表体字段进行赋值,可以取数据库中的值进行赋值
                        gridObj.phid = data[i].extendObjects.phid;
                        gridObj.u_sbqdbm = data[i].extendObjects.user_sbqd_no;
                        gridObj.u_sbqdmc = data[i].extendObjects.user_sbqd_name;
                        gridObj.u_supply = data[i].extendObjects.u_zb_supply;
                        gridObj.u_zb_rate = data[i].extendObjects.u_zb_rate;
                        gridObj.u_zb_prc_vat = data[i].extendObjects.u_zb_prc_vat;
                        gridObj.u_zb_prc = data[i].extendObjects.u_zb_prc;
                        gridObj.u_qdht_restqty = data[i].extendObjects.rest_qty;
                        gridObj.u_zbwsje = data[i].extendObjects.user_zbwsje
                        gridObj.u_zbhsje = data[i].extendObjects.user_zbhsje


                        gridObj.u_staus = data[i].extendObjects.u_staus;
                        gridObj.u_type = data[i].extendObjects.u_type;
                        gridObj.u_source = data[i].extendObjects.u_source;
                        gridObj.u_code = data[i].extendObjects.u_code;
                        gridObj.u_name = data[i].extendObjects.u_name;
                        gridObj.u_pnum = data[i].extendObjects.u_pnum;
                        gridObj.u_pname = data[i].extendObjects.u_pname;
                        gridObj.u_division = data[i].extendObjects.u_division;
                        gridObj.u_pline = data[i].extendObjects.u_pline;
                        gridObj.u_center = data[i].extendObjects.u_center;
                        gridObj.u_person = data[i].extendObjects.u_person;
                        gridObj.u_material_s = data[i].extendObjects.u_material_s;
                        gridObj.u_material_b = data[i].extendObjects.u_material_b;
                        gridObj.u_material_m = data[i].extendObjects.u_material_m;
                        gridObj.u_director = data[i].extendObjects.u_director;
                        gridObj.u_material_num = data[i].extendObjects.u_material_num;
                        gridObj.u_material_name = data[i].extendObjects.u_material_name;
                        gridObj.u_unit = data[i].extendObjects.u_unit;
                        gridObj.u_model = data[i].extendObjects.u_model;
                        gridObj.u_amt = data[i].extendObjects.u_amt;
                        gridObj.u_result = data[i].extendObjects.u_result;
                        gridObj.u_date = data[i].extendObjects.u_date;
                        gridObj.u_app_status = data[i].extendObjects.app_status;
                        gridObj.u_wf_flag = data[i].extendObjects.wf_flag;
                        gridObj.u_source_id = data[i].extendObjects.phid;
                        gridObj.u_source_table = data[i].extendObjects.resource_table;
                        gridObj.u_director_phid = data[i].extendObjects.u_director_phid;
                        gridObj.u_director_phid_EXName = data[i].extendObjects.u_director_name;
                        gridObj.phid_xl = data[i].extendObjects.phid_xl;
                        gridObj.u_djsj_dt = data[i].extendObjects.dj_dt;
                        gridObj.u_ps_prc_vat = data[i].extendObjects.ncg_prc_vat;
                        gridArr.push(gridObj);
                    }
                    //调用新增表体行数据的函数
                    dgrid.addRows(gridArr);
                });
            }
        }
    }

    // if (dgrid) {
    //   $NG.updateUI((updater) => {
    //     updater.editGrid.p_form_zyxqc_d1.u_director_phid.setProps({
    //       disabled: false, //只读
    //     });
    //   });
    //   // 设置字段隐藏
    //   let dgrid1HiddenFields = ["u_source_id", "u_source_table"];
    //   dgrid1HiddenFields.forEach((field) => {
    //     $NG.updateUI((updater) => {
    //       updater.editGrid.p_form_zyxqc_d1[field].setProps({
    //         hidden: true,
    //       });
    //     });
    //   });
    // }

    // const rows = dgrid.getSelectedData();
    // console.log(dgrid.getSelectedData());
    // dgrid.clearRows().then(() => {
    //   dgrid.addRows(rows);
    //   dgrid.refreshView();
    // });
});
